﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IGM.DataProvider;
using IGM.Framework.Commons;
using IGM.Framework.Constants;

namespace IGM.Presentation.Management
{
    public partial class GraduationManagement : UserControl
    {
        private readonly Business.Business _business;

        public GraduationManagement()
        {
            InitializeComponent();
            _business = Main.Main.Instance.IgmBusiness;
        }

        private void GraduationManagementLoad(object sender, EventArgs e)
        {
            LoadMajor();
            ChooseStudent();
            LoadStudent();
            Dock = DockStyle.Top;
        }

        private void LoadMajor()
        {
            cboMajors.DataSource = _business.GetListMajor();
            cboMajors.DisplayMember = PropertiesConstants.Name;
            cboMajors.ValueMember = PropertiesConstants.Id;
        }

        #region -- Choose student --

        private void ChooseStudent()
        {
            var students = _business.GetStudentQualityGraduation(Convert.ToInt32(((Major)cboMajors.SelectedItem).Id), 3, 7);
            txtCountStudents.Text = students.Count.ToString();
            foreach (var t in students)
            {
                var student = new StudentGraduation
                                  {
                                      IdStudent = t.Id,
                                      Project = "Chưa đăng ký.",
                                  };

                string message;

                if (_business.AddStudentGraduationValidator(student, out message))
                {
                    _business.AddStudentGraduation(student);

                    ReloadStudentGraduation(student);
                }
                else
                    return;
            }
        }
        #endregion
        /// <summary>
        /// 
        /// </summary>
        private void LoadStudent()
        {
            dgvStudents.DataSource = _business.GetListStudentGraduation();
            DataGridViewHelper.ShowHideColumns(dgvStudents,
                                               new[] { PropertiesConstants.IsChecked, "Code", "Name", "DateOfBirth", "Project" });
            DataGridViewHelper.ShowIsCheck(dgvStudents);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvStudents, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvStudents, new[] { "IsChecked", "Code", "Name", "DateOfBirth", "Project"},
                                                   new[] { "Chọn", "Mã sinh viên", "Họ và tên", "Ngày tháng năm sinh", "Đề tài"});

            if (dgvStudents != null)
            {
                dgvStudents.Columns["Code"].DisplayIndex = 1;
                dgvStudents.Columns["Name"].DisplayIndex = 2;
                dgvStudents.Columns["DateOfBirth"].DisplayIndex = 3;
                dgvStudents.Columns["Project"].DisplayIndex = 4;
            }
            StudentCurrentRowChanged();
        }

        private void StudentCurrentRowChanged()
        {
            if (dgvStudents.CurrentRow != null)
            {
                txtStudentName.Text = dgvStudents.CurrentRow.Cells["Name"].Value.ToString();
                txtStudentCode.Text = dgvStudents.CurrentRow.Cells["Code"].Value.ToString();
                txtThesis.Text = dgvStudents.CurrentRow.Cells["Project"].Value.ToString();
                //if (dtpBirthday != null)
                //    dtpBirthday.Value = (DateTime)dgvStudents.CurrentRow.Cells["DateOfBirth"].Value;               
            }

            else
            {
                txtStudentName.Text = txtStudentCode.Text = txtThesis.Text = string.Empty;
                ckbAllStudents.Checked = false;
                dtpBirthday.Value = DateTime.Now;
            }
        }

        private void CboMajorsSelectedIndexChanged(object sender, EventArgs e)
        {
            LoadStudent();
        }

        private void DgvStudentsCurrentCellChanged(object sender, EventArgs e)
        {
            StudentCurrentRowChanged();
        }

        private void DgvStudentsCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvStudents == null ||
               dgvStudents.Columns[(string)typeof(StudentGraduation).Properties().IsChecked] == null ||
               dgvStudents.Columns[(string)typeof(StudentGraduation).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvStudents[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvStudents[e.ColumnIndex, e.RowIndex].Value;

            ckbAllStudents.Checked = DataGridViewHelper.AllRowsIsCheck(dgvStudents);
        }

        private void CkbAllStudentsCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvStudents, ckbAllStudents.Checked);
        }

        private void ReloadStudentGraduation(StudentGraduation stundent)
        {
            LoadStudent();
            DataGridViewHelper.SetDgvCurrentCell(dgvStudents, stundent.Id.ToString());
            StudentCurrentRowChanged();
        }

         /// <summary>
        /// Event click button Add Student
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddStudentClick(object sender, EventArgs e)
        {
            //try
            //{
            //    var student = new Student
            //    {
            //        Name = txtStudentName.Text.Trim(),
            //        Code = txtStudentCode.Text.Trim(),
            //        IdMajor = (int)cboMajors.SelectedItem,
            //        DateOfBirth = dtpBirthday.Value,
            //    };

            //    string message;

            //    if (_business.AddStudentValidator(student, out message))
            //    {
            //        _business.AddStudent(student);

            //        ReloadStudentGraduation(student);
            //    }
            //    else
            //        MessageBox.Show(message);

            //}
            //catch (Exception ex)
            //{
            //    Logger.Write(null, ex);
            //}
        }

        /// <summary>
        /// Event click edit Major
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnEditStudentClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvStudents.CurrentRow != null)
                {
                    var student = new StudentGraduation
                    {
                        Id = Convert.ToInt32(dgvStudents.CurrentRow.Cells[PropertiesConstants.Id].Value),
                        IdStudent = Convert.ToInt32(dgvStudents.CurrentRow.Cells["IdStudent"].Value),
                        Project = txtThesis.Text.Trim()
                    };

                    if (!_business.EditStudentGraduation(student))
                    {
                        MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.ProgramName);
                        return;
                    }
                    ReloadStudentGraduation(student);
                }
                else
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click Delete Student Graduation
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteStudentClick(object sender, EventArgs e)
        {
            try
            {
                var students = new List<StudentGraduation>();
                string message;

                for (var i = 0; i < dgvStudents.RowCount; i++)
                {
                    if (!(bool)dgvStudents[(string)typeof(StudentGraduation).Properties().IsChecked, i].Value) continue;

                    students.Add(new StudentGraduation
                                     {
                                         Id = Convert.ToInt32(dgvStudents[(string)typeof(StudentGraduation).Properties().Id, i].Value),
                                         IdStudent = Convert.ToInt32(dgvStudents["IdStudent", i].Value),
                                         Project = dgvStudents["Project", i].Value.ToString(),
                                     });
                }
                if (students.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                if (_business.DeleteStudentGraduationsValidator(students, out message))
                {
                    if (
                        MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các sinh viên làm KLTN đã chọn"),
                                        FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteStudentGraduations(students);
                        ReloadStudentGraduation(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }
    }
}
